<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="renderer" content="webkit|ie-comp|ie-stand">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
  <meta http-equiv="Cache-Control" content="no-siteapp" />
  <title>仪表看板</title>
</head>

<body>
  <div id="app" v-loading.fullscreen.lock="loading">
    <div class="title">
      <span class="company">{{comapnyName}}</span>
      <div class="btns">
        <el-button size="small" @click="toBack">回到首页</el-button>
      </div>
    </div>
    <div class="energy-board-content">
      <template v-for="(energyList,rowIndex) in pageEnergyList">
        <div :key="`energyRow_${rowIndex}`" :class="{'is-last-line':(rowIndex+1)%rowNum===0}" :style="{height:`calc(${100/rowNum}% - 3px`}">
          <template v-for="(energy,index) in energyList">
            <energy-item v-if="energy!==null" :key="energy.no" :energy="energy" :is-show="getHasShow(rowIndex)"
              :chart-start-date="showDateList[showStartDateIndex]"></energy-item>
            <div v-else :key="'energy_'+index" class="energy-item"></div>
          </template>
        </div>
      </template>
    </div>
  </div>
</body>

<script src="https://upload.shinehao.com.cn/20190223085008echarts.min.4.2.1-rc.1.js"></script>
<script src="../../myJs/importFile.js"></script>
<script>
  importFile([
    "./css/energyItem.css"
  ], [
    "/vueSystem/js/promiseMethodUtil.js",
    "/vueSystem/models/baseModel.js"
  ]);

</script>
<script src="./models/energyModel.js"></script>
<script src="./energyItem.js"></script>
<script>
  var app = new Vue({
    el: '#app',

    watch: {
      currentRowIndex: function (newVal, oldVal) {
        var $content = $(this.$el).find('.energy-board-content');
        var scrollTop = $content.scrollTop();
        var top = $content.find(`>div:eq(${newVal})`).position().top;
        scrollTop += top;

        if (this.nonAnimate) {
          this.nonAnimate = false;
          $content.scrollTop(scrollTop);
          return;
        }

        var self = this;
        $content.animate({
          scrollTop: scrollTop
        }, 1000, function () {
          if (newVal === self.totalRow - self.rowNum) {
            self.currentRowIndex = 0;
            self.nonAnimate = true;
          }
        });
      }
    },

    data: function () {
      return {
        loading: false,
        basePath: SysUtil.getBasePath(),
        comapnyName: '',
        energyList: [],
        pageEnergyList: [],
        rowNum: 2,
        colNum: 3,
        currentRowIndex: 0,
        showDateList: this.getShowDateList(),
        showStartDateIndex: 0,
        nonAnimate: false,
        hasAlert: true
      };
    },

    created: function () {
      this.loading = true;
      var self = this;
      Promise.all([
        this.setComapnyName(),
        this.setEnergyList(true)
      ]).then(function () {
        self.toPageEnergyList();
        self.loading = false;
        self.hasAlert = false;
        self.boardRuning();
      });
    },

    methods: {
      getShowDateList: function () {
        var showDateList = [];
        var dateMoment = moment().startOf('month');
        var maxMoment = moment().subtract(9, 'day');
        while (maxMoment.isSameOrAfter(dateMoment)) {
          showDateList.push(dateMoment.format('YYYY-MM-DD'));
          dateMoment.add(1, 'day');
        }
        return showDateList;
      },

      setComapnyName: function () {
        var self = this;
        return ajaxRequest('user/getUserName').then(function (user) {
          self.comapnyName = user.company;
          return user;
        }).catch(function () {
          return null;
        });
      },

      setEnergyList: function (hasBefore, isUpdate) {
        var promiseList = [this.setTodayEnerygyList];
        if (hasBefore) {
          promiseList.unshift({
            method: this.setBeforeDayEnerygyList,
            params: [isUpdate]
          });
        }

        var self = this;
        return PromiseMethodUtil.queuePromise(promiseList).then(function (res) {
          if (hasBefore && self.currentRowIndex !== 0) {
            self.currentRowIndex = 0;
            self.nonAnimate = true;
          }
          return res;
        }).catch(function () {
          return null;
        });
      },

      setBeforeDayEnerygyList: function (isUpdate) {
        var postData = {};
        if (isUpdate) {
          postData.isUpdate = true;
        }
        var self = this;
        return ajaxRequest('energy/getEnergyTodayBeforeData', postData, true, this.hasAlert).then(
          function (energyList) {
            energyList = _.map(energyList, function (energy) {
              energy = new EnergyModel(energy);
              return energy;
            });
            self.energyList = energyList;
            return energyList;
          });
      },

      setTodayEnerygyList: function () {
        var energyList = this.energyList;
        var self = this;
        return ajaxRequest('energy/getEnergyTodayData', {}, true, this.hasAlert).then(function (todayEnergyList) {
          if (todayEnergyList.length !== energyList.length) {
            return self.setEnergyList(true, true);
          }

          var todayEnergyGroup = _.groupBy(todayEnergyList, 'no');
          var len = energyList.length;
          for (var i = 0; i < len; i++) {
            var energy = energyList[i];
            var todayEnergy = todayEnergyGroup[energy.no];
            if (todayEnergy === undefined) {
              continue;
            }
            energy.refreshData(todayEnergy[0]);
          }
          return energyList;
        });
      },

      toPageEnergyList: function () {
        var energyList = this.energyList;
        var pageEnergyList = [];
        var colNum = this.colNum;
        var rowNum = this.rowNum;
        var totalRow = energyList.length / colNum;
        totalRow = _.round(totalRow, 1);
        totalRow = Math.ceil(totalRow);
        totalRow = totalRow < rowNum ? rowNum : totalRow;
        for (var i = 0; i < totalRow; i++) {
          pageEnergyList.push([]);
        }

        var lastRow = 0;
        for (var i = 0; i < energyList.length; i++) {
          var energy = energyList[i];
          var rowIndex = i / colNum;
          rowIndex = Math.floor(rowIndex);
          energy = _.cloneDeep(energy);
          pageEnergyList[rowIndex].push(energy);
          if (i === energyList.length - 1) {
            lastRow = rowIndex;
          }
        }

        var lastEnergy = pageEnergyList[lastRow];
        if (lastEnergy.length > 0) {
          for (var i = lastEnergy.length; i < colNum; i++) {
            lastEnergy.push(null);
          }
        }

        if (totalRow > rowNum) {
          var num = totalRow % rowNum;
          if (num !== 0) {
            for (var i = 0; i < num; i++) {
              var array = [];
              for (var i = 0; i < colNum; i++) {
                array.push(null)
              }
              pageEnergyList.push(array);
            }
          }
          for (var i = 0; i < rowNum; i++) {
            pageEnergyList.push(pageEnergyList[i]);
          }
        }

        this.totalRow = pageEnergyList.length;
        this.pageEnergyList = pageEnergyList;
      },

      getHasShow: function (rowIndex) {
        var rowNum = this.rowNum;
        var totalRow = this.totalRow;
        if (rowNum >= totalRow) {
          return true;
        }

        var currentRowIndex = this.currentRowIndex;
        if (rowIndex >= currentRowIndex && rowIndex <= currentRowIndex + rowNum - 1) {
          return true;
        }
        return false;
      },

      toBack: function () {
        var basePath = this.basePath;
        location.href = basePath + "/datav/index.html?autoLogin=autoLogin";
      },

      boardRuning: function () {
        this.scrollRuning();
        this.energyRecordsRuning();
        this.resetEnergyListRuning();
      },

      scrollRuning: function () {
        var self = this;

        setTimeout(function () {
          self.toNextPage();
          self.scrollRuning();
        }, 10500);
      },

      toNextPage: function () {
        var currentRowIndex = this.currentRowIndex;
        var totalRow = this.totalRow;
        var rowNum = this.rowNum;
        if (totalRow <= rowNum) {
          return;
        }

        this.currentRowIndex = (currentRowIndex + this.rowNum) % totalRow;
      },

      energyRecordsRuning: function () {
        var self = this;
        setTimeout(function () {
          var showStartDateIndex = self.showStartDateIndex;
          var showDateList = self.showDateList;
          if (showDateList.length === 0) {
            self.showStartDateIndex = 0;
            return;
          }
          var index = (showStartDateIndex + 1) % showDateList.length;
          self.showStartDateIndex = index;
          self.energyRecordsRuning();
        }, 5000);
      },

      resetEnergyListRuning: function () {
        var self = this;
        var nextMoment = moment().startOf('day').set({
          hour: 6
        });
        if (moment().isAfter(nextMoment, 'minute')) {
          nextMoment.add(1, 'day');
        }
        var rangeTime = nextMoment.diff(moment());
        var regTime = 15 * 60 * 1000;

        var flag;
        if (rangeTime > regTime) {
          rangeTime = regTime;
          flag = false;
        } else {
          flag = true;
        }

        setTimeout(function () {
          self.setEnergyList(flag, true).then(function () {
            if (flag) {
              var showDateList = self.getShowDateList();
              self.showDateList = showDateList;
              var currentRowIndex = self.currentRowIndex;
              if (currentRowIndex >= showDateList.length) {
                self.currentRowIndex = 0;
              }
            }
            self.toPageEnergyList();
          });
          self.resetEnergyListRuning();
        }, rangeTime);
      }
    },

    components: {
      EnergyItem: EnergyItem
    }
  });

</script>
<style>
  #app {
    background: #0E2A43;
  }

  .title {
    height: 43px;
    text-align: center;
    background-size: 176px 40px;
    background-repeat: no-repeat;
    background-color: #000;
    position: relative;
  }

  .title .btns {
    position: absolute;
    right: 10px;
    top: 0;
    padding-top: 5px;
  }

  .title .company {
    color: #ffffff;
    font-size: 20px;
    line-height: 43px;
  }

  .energy-board-content {
    height: calc(100% - 53px);
    overflow: hidden;
    margin: 5px;
    position: relative;
  }

  .energy-board-content>div {
    margin-bottom: 6px;
    display: flex;
  }

  .energy-board-content>div.is-last-line {
    margin-bottom: 0;
  }

  .energy-board-content .energy-item {
    flex: 1;
    margin-right: 5px;
  }

  .energy-board-content .energy-item:last-child {
    margin-right: 0;
  }

</style>

</html>
